using dotnet_ef_admin.Src.Utilities;
using Microsoft.EntityFrameworkCore;
using StackExchange.Redis;

namespace dotnet_ef_admin.Src.Services;

public class AuthService : IAuthService {
    private readonly DbCtx _context;
    private readonly JwtService _jwtService;
    private readonly IConnectionMultiplexer _redis;

    public AuthService(DbCtx context, IConnectionMultiplexer redis, JwtService jwtService) {
        _context = context;
        _redis = redis;
        _jwtService = jwtService;
    }

    public async Task<LogoutResult> LogoutAsync(string token) {
        // 从JWT 中获取用户ID
        var userId = _jwtService.GetUserIdFromToken(token);

        // 从 Redis 中删除会话信息
        var db = _redis.GetDatabase();
        var cacheKey = $"session:{userId}";
        await db.KeyDeleteAsync(cacheKey);

        return new LogoutResult { IsSuccess = true, Message = "注销成功" };
    }

    public async Task<LoginResult?> LoginAsync(LoginRequest request) {
        var user = await _context.Users.FirstOrDefaultAsync(u =>
            u.Username == request.Username && u.Password == request.Password);

        if (user == null) return null;

        // 使用 Redis 作为会话存储
        var db = _redis.GetDatabase();
        var cacheKey = $"session:{user.Id}";
        await db.StringSetAsync(cacheKey, "active", TimeSpan.FromHours(1)); // 设置会话有效期为1小时

        // 这里可以添加生成身份验证令牌或设置会话信息的逻辑
        // 生成JWT
        var token = _jwtService.GenerateToken(user.Id);

        return new LoginResult {
            AccessToken = $"Bearer {token}"
        };
    }
}